package com.ruoyi.web.controller.hrm;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.FileUploadInfo;
import com.ruoyi.system.domain.PropertyAccount;
import com.ruoyi.system.domain.PropertyContract;
import com.ruoyi.system.domain.PropertyInfo;
import com.ruoyi.system.service.IFileUploadService;
import com.ruoyi.system.service.IPropertyInfoService;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @date 2021-07-05
 */
@Controller
@RequestMapping("/hrm/propertyInfo")
public class PropertyInfoController extends BaseController
{
    @Autowired
    private IPropertyInfoService propertyInfoService;

    @Autowired
    private IFileUploadService fileUploadService;

    private String prefix = "hrm/propertyInfo";

    @GetMapping()
    public String toMain(ModelMap modelMap) {
        return prefix + "/main";
    }

    /**
     * 人员信息列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(PropertyInfo propertyInfo)
    {
        startPage();
        List<PropertyInfo> propertyInfoList = propertyInfoService.selectPropertyInfoList(propertyInfo);
        //统计附件数
        for (PropertyInfo pi:propertyInfoList) {
            Integer count = fileUploadService.getFileCountByKey(pi.getInfoId());
            pi.setFileCount(count);
        }
        return getDataTable(propertyInfoList);
    }

    /**
     *   跳转新增
     */
    @GetMapping("/add")
    public String toAdd(ModelMap modelMap){
        return prefix + "/add";
    }

    /**
     *   保存新增
     */
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(PropertyInfo propertyInfo) {
        try{
            propertyInfoService.insertPropertyInfo(propertyInfo);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("新增失败");
        }
        return AjaxResult.success();
    }

    /**
     * 跳转上传页面
     */
    @GetMapping("/toUpload/{infoId}")
    public String toUpload(@PathVariable String infoId, ModelMap modelMap) {
        List<FileUploadInfo> fileUploadInfoList = fileUploadService.getFileUploadListByKey(infoId);
        modelMap.put("infoId",infoId);
        modelMap.put("fileInfos",fileUploadInfoList);
        return prefix + "/infoUpload";
    }

    /**
     * 上传文件
     */
    @PostMapping("/infoUpload")
    @ResponseBody
    public AjaxResult infoUpload(MultipartFile file)
    {
        String filePath = "";
        try {
            filePath = FileUploadUtils.upload(Global.getPropertyInfoPath(),file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(file.getOriginalFilename(),filePath);
    }

    /**
     * 保存文件地址到库里
     */
    @PostMapping("/changePath")
    @ResponseBody
    public AjaxResult changePath(String infoId,String filePath,String fileName) {
        try{
            FileUploadInfo fileUploadInfo = new FileUploadInfo();
            fileUploadInfo.setFileId(UUID.randomUUID().toString().replaceAll("-",""));
            fileUploadInfo.setFileName(fileName);
            fileUploadInfo.setFilePath(filePath);
            fileUploadInfo.setFileType("2");  //人员信息
            fileUploadInfo.setStatus("1");  //有效
            fileUploadInfo.setBelongKey(infoId);
            fileUploadService.insertFileUpload(fileUploadInfo);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 将文件置为失效
     */
    @PostMapping("/removeAnnex")
    @ResponseBody
    public AjaxResult removeAnnex(String key) {
        //String InfoId,String filePath    目前用不上
        try{
            fileUploadService.deleteFile(key);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("文件删除失败");
        }
        return AjaxResult.success();
    }

    /**
     * 下载文件到指定目录
     */
    @PostMapping("/downloadInfo")
    @ResponseBody
    public AjaxResult downloadInfo(String infoId) {
        List<FileUploadInfo> fileUploadInfos = fileUploadService.getFileUploadListByKey(infoId);
        String infoPath = "/profile/propertyInfo";
        File dir = new File(Global.getDownloadPath()+infoId);//创建downloadPath文件
        if(!dir.exists()){
            dir.mkdirs();
        }
        if(fileUploadInfos!=null&&fileUploadInfos.size()>0){
            //执行循环将需要下载的文件拷贝到下载目录下
            for(FileUploadInfo fileUploadInfo:fileUploadInfos){
                String newPath = fileUploadInfo.getFilePath().replaceAll(infoPath,Global.getPropertyInfoPath());//Global.getPropertyInfoPath()里的profile是一个字段，profile存的是本地地址，不同服务器的地址不一样
                File file = new File(newPath);//源文件
                File newFile = new File(dir + File.separator + fileUploadInfo.getFileName());//目标文件
                try {
                    Files.copy(file.toPath(),newFile.toPath());
//                    fileUploadInfo.setFilePath(newFile.toPath().toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else{
            return AjaxResult.error("无附件！");
        }
        return AjaxResult.success("success",infoId);
    }

    /**
     * 将目录中的文件打包下载
     */
    @GetMapping("/downloadInfo")
    public void downloadInfo(String fileName, HttpServletRequest request, HttpServletResponse response) {
        try{
            PropertyInfo pi = propertyInfoService.getPropertyInfoById(fileName);
            String downloadName = pi.getName() + "人员信息附件.zip";
            String sourceFilePath = Global.getDownloadPath() + fileName;
            String zipOutFilePath = Global.getDownloadPath() + downloadName;
            FileUtils.createZip(sourceFilePath,zipOutFilePath);
            try{
                response.setHeader("Content-Type", "application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + FileUtils.setFileDownloadHeader(request,downloadName));
                FileUtils.writeBytes(zipOutFilePath,response.getOutputStream());
            }finally {
                try{
                    File zfile = new File(zipOutFilePath);
                    zfile.delete();
                    File sqlFile = new File(sourceFilePath);
                    FileUtils.deleteDir(sqlFile);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 跳转修改页面
     * @return
     */
    @GetMapping("/edit/{infoId}")
    public String toEdit(@PathVariable String infoId,ModelMap modelMap) {
        PropertyInfo propertyInfo = propertyInfoService.getPropertyInfoById(infoId);
        modelMap.put("propertyInfo",propertyInfo);
        return prefix + "/edit";
    }

    /**
     * 保存修改
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(PropertyInfo propertyInfo) {
        try{
            propertyInfoService.updatePropertyInfo(propertyInfo);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("修改失败");
        }
        return AjaxResult.success();
    }

    /**
     * 删除
     * @return
     */
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try{
            propertyInfoService.removePropertyInfo(ids);
            fileUploadService.deleteAll(ids);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("删除失败");
        }
        return AjaxResult.success();
    }

    /**
     *
     *导出
     * @return
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(PropertyInfo propertyInfo, String ids) {
        List<PropertyInfo> piList = new ArrayList<>();
        if(StringUtils.isNotEmpty(ids)){
            String[] infoIds = Convert.toStrArray(ids);
            for(String infoId:infoIds){
                PropertyInfo pi = propertyInfoService.getPropertyInfoById(infoId);
                piList.add(pi);
            }
        }else{
            piList = propertyInfoService.selectPropertyInfoList(propertyInfo);
        }
        ExcelUtil<PropertyInfo> util = new ExcelUtil(PropertyInfo.class);
        return util.exportExcel(piList, "人员信息");
    }

    /**
     * 导入
     * @return
     */
    @PostMapping("/import")
    @ResponseBody
    public AjaxResult importPropertyInfo(MultipartFile file)  {
        ExcelUtil<PropertyInfo> util = new ExcelUtil<>(PropertyInfo.class);
        List<PropertyInfo> lists = null;
        try {
            lists = util.importExcel(file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("excel解析错误");
        }
        //校验数据
        String message =propertyInfoService.importPropertyInfo(lists);
        return AjaxResult.success(message);
    }

    /**
     * 下载人员信息模板
     * @return
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<PropertyInfo> util = new ExcelUtil<PropertyInfo>(PropertyInfo.class);
        return util.importTemplateExcel("人员信息");
    }

}
